// Ajax object
var ajax;

// returns a new ajax objet
function getNewAjaxObject() {
	if (window.XMLHttpRequest) {
		ajax = new XMLHttpRequest(); // No Internet Explorer
	} else {
		ajax = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer
	}
	return ajax;
}

window.fbAsyncInit = function() {
	FB.init({
		appId : '438000279595372', // App ID Prox
		channelUrl : 'channel.html', // Channel File
		status : true, // check login status
		cookie : true, // enable cookies to allow the server to access the
		// session
		xfbml : true, // parse XFBML
		logging : true
	// to enable logging
	});
	FB.Event.subscribe('auth.statusChange', handleStatusChange);
	// Load the SDK Asynchronously
};
// Load the SDK Asynchronously
(function(d) {
	var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
	if (d.getElementById(id)) {
		return;
	}
	js = d.createElement('script');
	js.id = id;
	js.async = true;
	js.src = "//connect.facebook.net/en_US/all.js";
	ref.parentNode.insertBefore(js, ref);
}(document));


/**
 * One your status change this function will be triggered
 * 
 */
function handleStatusChange(response) {
	document.body.className = response.authResponse ? 'connected'
			: 'not_connected';

	// if we are logged in
	if (response.authResponse) {
		FB.api('/me', function(response) {
			var locale = response.locale;
			var username = response.username;
			var name = response.name;
			var email = response.email;
			var location = response.location.name;
			localStorage.username = username;
			console.log(response.id + ' ' + username + ' ' + name + ' ' + email
					+ ' ' + location + ' ' + locale);
			
			document.getElementById('index_login_button').style.display = 'none';
			// TODO llamar al backend para ver si soy admin
		});
	} else {
		console.log(response);
	}
}

(function(d) {
	var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
	if (d.getElementById(id)) {
		return;
	}
	js = d.createElement('script');
	js.id = id;
	js.async = true;
	js.src = "//connect.facebook.net/en_US/all.js";
	ref.parentNode.insertBefore(js, ref);
}(document));

/**
 * Function invoked by a button, it will popup the login window to FB
 * 
 */
function loginUser() {
	FB.login(function(response) {
	}, {
		scope : 'email,user_actions.music'
	});

}